#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <map>
#include <bits/stdc++.h>
#include "HCNetSDK.h"
#include "ptz.hpp"

using namespace std;


const char * PTZHelper::None = "None";

PTZHelper::PTZHelper(int argc, char *argv[])
{
    int opt; //getopt()的返回值
    // c - channel's number
    // d - director of moving
    // a - action (stop/start)
    // r - recorder (nvr ip address)
    // u - username
    // p - password
    const char *opt_string = "c:d:a:r:u:p:"; //设置短参数类型及是否需要参数值    
    while ((opt=getopt(argc, argv, opt_string)) != -1)
    {
        this->params.push_back(CMD_Param(opt, optarg));
    }
	init_move_director();
}

//获取参数值
const char* PTZHelper::get_opt_value(const char key)
{
    for(std::vector<CMD_Param>::iterator it=this->params.begin(); it!=params.end(); it++ )
    {
        if(it->PName == key) {
            return it->PValue;
        }
    }
    return None;
}

//判断值是否为None
bool PTZHelper::is_none(const char* value) {
    return strcmp(value, None)==0;
}

//初始化PTZ的map
void PTZHelper::init_move_director()
{
	if ( MOVE_DIRECTOR.size() > 0 ) return;
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("left",	PAN_LEFT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("right",	PAN_RIGHT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("up",		TILT_UP));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("down",	TILT_DOWN));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("up_left",	UP_LEFT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("up_right",	UP_RIGHT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("down_left",	DOWN_LEFT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("down_right",	DOWN_RIGHT));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("zoom_in",		ZOOM_IN));
	MOVE_DIRECTOR.insert(std::pair<const char*, int>("zoom_out",	ZOOM_OUT));
}

// 获取PTZ参数（移动方向、缩放）
int PTZHelper::get_director(const char* key) {
	std::map<const char*, int>::iterator it = MOVE_DIRECTOR.begin();
	for(; it != MOVE_DIRECTOR.end(); it++ )
	{
		if ( strcmp(it->first, key) == 0 ) return it->second;
	}
	return -1;
}

// 获取PTZ参数（移动方向、缩放）
int PTZHelper::director() {
	const char* k = get_opt_value(cmd_param_ptz);
	return get_director(k);
}

// 获取PTZ动作（开始/停止）
int PTZHelper::action() {
	const char* act = get_opt_value(cmd_param_action);
	if ( strcmp(act, CMD_START) == 0 ) return 1;
	else if ( strcmp(act, CMD_STOP) == 0 ) return 0;
	else return -1;
}

// 获取NVR通道号
int PTZHelper::channel() {
	return atoi(get_opt_value(cmd_param_channel));
}


